﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Survey.DataAccessLayer.Data;
using Survey.Entity;

namespace Survey.DataAccessLayer
{
    public class QuestionAccessor : Accessor<Question>
    {
        private QuestionOptionAccessor _optionAccessor;
        private QuestionFeedbackAccessor _feedbackAccessor;
        public QuestionAccessor() : base(new SurveyDbContext()) {
            _optionAccessor = new QuestionOptionAccessor();
            _feedbackAccessor = new QuestionFeedbackAccessor();
        }
        public Question GetQuestion(int id)
        {
            var q = Select(question => question.Id == id);
            return q.Single();
        }
        /// <summary>
        /// 返回选择题的选择次数
        /// </summary>
        /// <param name="question"></param>
        /// <returns>key: 选项Id, value: 选择次数</returns>
        public IEnumerable<KeyValuePair<int, int>> GetFeedbackCount(Question question)
        {
            Dictionary<int, int> returnVal = new Dictionary<int, int>();
            foreach (QuestionOption o in question.QuestionOptionCollection)
            {
                int count = _feedbackAccessor.Select(f=>f.QuestionOptionId==o.Id).Count();
                returnVal.Add(o.Id, count);
            }
            return returnVal;
        }
        public IEnumerable<KeyValuePair<int, int>> GetFeedbackCount(int questionId)
        {
            Question question = Select(q => q.Id == questionId).Single();
            return GetFeedbackCount(question);
        }
        /// <summary>
        /// 返回主观问题回答的描述
        /// </summary>
        /// <param name="question"></param>
        /// <returns>key: 问题Id, value: 描述</returns>
        public IEnumerable<KeyValuePair<int, string>> GetFeedbackString(Question question)
        {
            Dictionary<int, string> returnVal = new Dictionary<int, string>();
            foreach (QuestionOption option in question.QuestionOptionCollection)
            {
                var query = _feedbackAccessor.Select(f => f.QuestionOptionId == option.Id);
                foreach (var item in query)
                {
                    string describe = item.RefQuestionOption.Describe;
                    returnVal.Add(question.Id, describe);
                }
            }
            return returnVal;
        }
    }
}
